package com.chart.common.utils;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.List;
import java.util.Map;

/**
 * 文件导出excel 和cxv
 *
 * @author 罗继全
 * 2024/7/4 16:28
 */
public class FileUtil {
       //不读第一行
    public void exportExcelWithoutFirstRow(HttpServletResponse response, List<Map<String, Object>> dataList, String fileName) throws IOException {
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("Sheet1");

        // 填充数据行
        int rowIndex = 0; // 修改为0，不创建标题行
        for (Map<String, Object> dataMap : dataList) {
            Row row = sheet.createRow(rowIndex++);
            int cellIndex = 0;
            for (Object value : dataMap.values()) {
                Cell cell = row.createCell(cellIndex++);
                cell.setCellValue(value != null ? value.toString() : "");
            }
        }

        // 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName + ".xlsx");

        // 获取响应的输出流
        ServletOutputStream outputStream = response.getOutputStream();

        // 将工作簿写入输出流
        workbook.write(outputStream);

        // 关闭工作簿和输出流
        workbook.close();
        outputStream.flush();
        outputStream.close();
    }
    public void exportCsvWithoutHeader(HttpServletResponse response, List<Map<String, Object>> dataList, String fileName) throws IOException {
        response.setContentType("text/csv");
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName + ".csv");

        ServletOutputStream outputStream = response.getOutputStream();
        OutputStreamWriter writer = new OutputStreamWriter(outputStream, "UTF-8");

        // 不写入CSV头部，直接写入数据行
        for (Map<String, Object> dataMap : dataList) {
            writeLine(writer, dataMap.values());
        }

        writer.flush();
        writer.close();
        outputStream.flush();
        outputStream.close();
    }
/* public void exportCsv(HttpServletResponse response, List<Map<String, Object>> dataList, String fileName) throws IOException {

     response.setContentType("text/csv");
     response.setHeader("Content-Disposition", "attachment; filename=" + fileName + ".csv");

     ServletOutputStream outputStream = response.getOutputStream();
     OutputStreamWriter writer = new OutputStreamWriter(outputStream, "UTF-8");

     // 写入 CSV 头部
     if (!dataList.isEmpty()) {
         writeLine(writer, dataList.get(0).keySet());
     }

     // 写入数据行
     for (Map<String, Object> dataMap : dataList) {
         writeLine(writer, dataMap.values());
     }

     writer.flush();
     writer.close();
     outputStream.flush();
     outputStream.close();
 }*/

    private void writeLine(OutputStreamWriter writer, Iterable<?> values) throws IOException {
        boolean firstValue = true;
        for (Object value : values) {
            if (!firstValue) {
                writer.write(",");
            }
            writer.write(formatCsvField(value.toString()));
            firstValue = false;
        }
        writer.write("\n");
    }

    private String formatCsvField(String field) {
        if (field.contains(",") || field.contains("\"") || field.contains("\n")) {
            // 如果字段中包含逗号、双引号或换行符，需要用双引号包裹，并内部的双引号需要转义为两个双引号
            return "\"" + field.replaceAll("\"", "\"\"") + "\"";
        } else {
            return field;
        }
    }
}
